package com.sc.site.goods;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sc.dal.common.pagination.PaginationBean;
import com.sc.dal.dto.promotion.PromotionDetailDto;
import com.sc.dal.dto.promotion.PromotionGoodsSkuDto;
import com.sc.dal.mapper.goods.GoodsMapper;
import com.sc.dal.model.consultComment.ConsultComment;
import com.sc.dal.model.favorites.Favorites;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsBrand;
import com.sc.dal.model.goods.GoodsClass;
import com.sc.dal.model.member.Member;
import com.sc.service.consultComment.ConsultCommentService;
import com.sc.service.goods.GoodsBrandService;
import com.sc.service.goods.GoodsClassService;
import com.sc.service.goods.GoodsService;
import com.sc.service.member.MemberService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.data.Common;
import com.sc.util.data.DataUtil;
import com.sc.util.data.DateUtil;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;

@RequestMapping(value="/goods")
@Controller
public class GoodsController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsBrandService goodsBrandService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private GoodsClassService goodsClassService;
	@Autowired
	private ConsultCommentService consultCommentService;
	@Autowired
	private PromotionService promotionService;
	
	/**
	 * 产品中心
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="productCenter")
	public Object productCenter(HttpServletRequest request,Integer currPage, Integer pageSize){
		ModelAndView mav = new ModelAndView("/goods/productCenter");
		List<Map<String, Object>> resultList = null;
		int totalRecords = 0;
		int totalPage = 0;
		pageSize = 50;
		//参数
		Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
		//商品品牌参数
		Map<String,Object> paramBrand = new LinkedHashMap<String,Object>();
		String search = request.getParameter("search");

		if(StringUtils.isNotBlank(search)){
			paramMap.put("search", search);
		}
		String brandByText = request.getParameter("brandByText");
		String brand = request.getParameter("id");
		String classId = request.getParameter("classId");
		String className = request.getParameter("className");
		if(StringUtils.isNotBlank(brand)){
			paramMap.put("brand", brand);
		}
		//查询商品分类
		if(StringUtils.isNotBlank(classId)){
			paramMap.put("classId", classId);
			//查询商品分类【根据分类ID查询子级分类】
			List<GoodsClass> goodsClassList = goodsClassService.selectByGoodsClassList(new Integer(classId));
			if(goodsClassList.size()>0){
				mav.addObject("goodsClassList", goodsClassList);
			}else{
				mav.addObject("goodsClassList", "null");
			}
			mav.addObject("className", className);
			mav.addObject("classId", classId);
		}else{
			//查询商品分类
			List<GoodsClass> goodsClassList = goodsClassService.selectByGoodsClass();
			mav.addObject("className", "null");
			mav.addObject("goodsClassList", goodsClassList);
		}
		try{
			paramMap.put("sort", "1");
			//搜索商品
			PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count", "selectList", GoodsMapper.class);
			
			resultList = paginationBean.getPageList();
			   for (int i = 0; i < resultList.size(); i++) {
					Goods goods = (Goods) resultList.get(i);
					Integer id = goods.getId();
					String goodsType = goods.getType();
					/***获取该商品的月销量****************/
					int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(id);	
					goods.setMonthSaleMount(String.valueOf(monthSaleMount));

					Map<String, Object> map = new LinkedHashMap<String, Object>();
			    	map.put("goodsId", id);
					String proTitle="";
					if(goodsType!=null){
						String goodstypeTemp[] = goodsType.split("-");
						for(int j =0;j<goodstypeTemp.length;j++ ){
							if("09".equals(goodstypeTemp[j])){
								proTitle="包邮、";
							}
				         }
					}
					proTitle += promotionService.getGoodsByPromtion(map);
					/**  截取字段*/
					if(proTitle.endsWith("、")){
						proTitle = proTitle.substring(0, proTitle.length()-1);
					}
					goods.setProTitle(proTitle);
				}		

			totalRecords = paginationBean.getTotalRecords();
			totalPage = paginationBean.getTotalPage();
			int currentPage = paginationBean.getCurrentPage(); //获取当前页数
			mav.addObject("resultList", resultList);
			mav.addObject("totalRecords", totalRecords);
			mav.addObject("totalPage", totalPage);
			mav.addObject("currentPage", currentPage);
			//查询商品品牌
			List<GoodsBrand> brandList = goodsBrandService.selectList(paramBrand);
			mav.addObject("brandList", brandList);
			logger.info("分页查找商品成功！");
		}catch(Exception e){
			logger.error("分页查找商品失败！"+e);
			throw new ScBizException("分页查找商品错误！", e);
		}
		
		return mav;

	}
	
	/**
	 * 根据综合排序：人气、销量、信用、价格。
	 * 产品中心 【根据关键条件查询结果信息】
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="productCenterList")
	@ResponseBody
	public Object productCenterList(HttpServletRequest request,Integer currPage, Integer pageSize){
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> resultList = null;
		String brandName = request.getParameter("brandName");
		String brand = request.getParameter("id");  //品牌Id
		String classId = request.getParameter("classId"); //商品分类Id
		String type = request.getParameter("type");	  //排序
		String chkValue = request.getParameter("chkValue"); //复选框过滤
		String searchName = request.getParameter("searchName"); //搜索框
		int totalRecords = 0;
		int totalPage = 0;
		pageSize = 50;
		//参数
		Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
		String search = request.getParameter("search");
		if(Common.isNotEmpty(search)){
			paramMap.put("search", search);
		}
		if(Common.isNotEmpty(brand)){
			paramMap.put("brand", brand);
		}
		if(Common.isNotEmpty(searchName)){
			paramMap.put("searchName", searchName);
		}
		if(Common.isNotEmpty(type)){
			//01 人气查询
			if("01".equals(type)){
				paramMap.put("type", type);
			// 3：销量从高到低   4：价格升序	
			}else{
				paramMap.put("sort", type);
			}
		}
//		if(StringUtils.isNotBlank(chkValue)){
		if(Common.isNotEmpty(chkValue)){
			String temp[] = chkValue.split(",");
			String value = "";
			for (int i = 0; i < temp.length; i++) {
				value+="'"+temp[i]+"',";
			}
			value = value.substring(0, value.length()-1);
			paramMap.put("chkValue", value);
		}
		if(Common.isNotEmpty(classId)){
			paramMap.put("classId", classId);
			//查询商品分类【根据分类ID查询子级分类】
			List<GoodsClass> goodsClassList = goodsClassService.selectByGoodsClassList(new Integer(classId));
			map.put("goodsClassList", goodsClassList);
		}else{
			map.put("goodsClassList", "null");
		}
		try{
			//搜索商品
			PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count", "selectList", GoodsMapper.class);
//			resultList = paginationBean.getPageList();
			resultList = this.getGoodsByFavourable(paginationBean.getPageList());
			totalRecords = paginationBean.getTotalRecords();
			totalPage = paginationBean.getTotalPage();
			int currentPage = paginationBean.getCurrentPage(); //获取当前页数
			map.put("resultList", resultList);
			map.put("brandName", brandName);
			map.put("totalRecords", totalRecords);
			map.put("totalPage", totalPage);
			map.put("currentPage", currentPage);
			
			//mav.addObject("goodsClassList", goodsClassList);
			/*mav.addObject("resultList", resultList);
			mav.addObject("brandName", brandName);
			mav.addObject("totalRecords", totalRecords);
			mav.addObject("totalPage", totalPage);
			mav.addObject("currentPage", currentPage);*/
			logger.info("分页查找商品成功！");
		}catch(Exception e){
			logger.error("分页查找商品失败！"+e);
			throw new ScBizException("分页查找商品错误！", e);
		}
//		return mav;
		return map;
	}
	
	
	/**
	 * 产品中心----分类查询
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="productCenterClass")
	public Object productCenterClass(HttpServletRequest request,Integer currPage, Integer pageSize){
		ModelAndView mav = new ModelAndView("/goods/productCenter");
		List<Map<String, Object>> resultList = null;
		int totalRecords = 0;
		int totalPage = 0;
		pageSize = 50;
		//参数
		Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
		//商品品牌参数
		Map<String,Object> paramBrand = new LinkedHashMap<String,Object>();
		String search = request.getParameter("search");

		if(StringUtils.isNotBlank(search)){
			paramMap.put("search", search);
		}
		String brandByText = request.getParameter("brandByText");
		String brand = request.getParameter("id");
		if(StringUtils.isNotBlank(brand)){
			paramMap.put("brand", brand);
		}
		try{
			//搜索商品
			PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count", "selectList", GoodsMapper.class);
			
			resultList = paginationBean.getPageList();
			totalRecords = paginationBean.getTotalRecords();
			totalPage = paginationBean.getTotalPage();
			int currentPage = paginationBean.getCurrentPage(); //获取当前页数
			mav.addObject("resultList", resultList);
			mav.addObject("totalRecords", totalRecords);
			mav.addObject("totalPage", totalPage);
			mav.addObject("currentPage", currentPage);
			//查询商品分类
			List<GoodsClass> goodsClassList = goodsClassService.selectByGoodsClass();
			mav.addObject("goodsClassList", goodsClassList);
			//查询商品品牌
			List<GoodsBrand> brandList = goodsBrandService.selectList(paramBrand);
			
			mav.addObject("brandList", brandList);
			  for (int i = 0; i < resultList.size(); i++) {
				    
					Goods goods = (Goods) resultList.get(i);
					Integer id = goods.getId();
					String goodsType = goods.getType();
					//***获取该商品的月销量****************//
					int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(id);	
					goods.setMonthSaleMount(String.valueOf(monthSaleMount));
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("goodsId", id);
					String proTitle="";
					if(goodsType!=null){
						String goodstypeTemp[] = goodsType.split("-");
						for(int j =0;j<goodstypeTemp.length;j++ ){
							if("09".equals(goodstypeTemp[j])){
								proTitle="包邮、";
							}
				         }
					}
					proTitle += promotionService.getGoodsByPromtion(map);
					/**  截取字段*/
					if(proTitle.endsWith("、")){
						proTitle = proTitle.substring(0, proTitle.length()-1);
					}
					goods.setProTitle(proTitle);
				}
			logger.info("分页查找商品成功！");
		}catch(Exception e){
			logger.error("分页查找商品失败！"+e);
			throw new ScBizException("分页查找商品错误！", e);
		}
		
		return mav;

	}
	/**
	 * 
	 * 热销产品
	 * 初始化页面数据
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="hotSale", method=RequestMethod.GET)
	public Object hotSale(HttpServletRequest request,Integer currPage, Integer pageSize){
		ModelAndView mav = new ModelAndView("/goods/hot_sale");
		List<Map<String, Object>> resultList = null;
		int totalRecords = 0;
		int totalPage = 0;
		pageSize = 50;
		//参数
		Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
		String search = request.getParameter("search");
		if(StringUtils.isNotBlank(search)){
			paramMap.put("search", search);
		}
		//（01：特别推荐(新品)、02：新品热销、03:特价商品、04：潮流热销、09：包邮）
		paramMap.put("type", "02");
		try{
			//搜索商品
			PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count", "selectList", GoodsMapper.class);
//			resultList = paginationBean.getPageList();
			totalRecords = paginationBean.getTotalRecords();
			totalPage = paginationBean.getTotalPage();
			//组装商品月销量、优惠信息
			resultList = this.getGoodsByFavourable(paginationBean.getPageList());
			request.setAttribute("resultList", resultList);
			request.setAttribute("totalRecords", totalRecords);
			request.setAttribute("totalPage", totalPage);
			paramMap.put("type", "04");
			PaginationBean<Map<String,Object>> paginationBeanT = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count", "selectList", GoodsMapper.class);
//			List<Map<String, Object>> resultListT = paginationBeanT.getPageList();
			List<Map<String, Object>> resultListT = this.getGoodsByFavourable(paginationBeanT.getPageList());
			request.setAttribute("resultListT", resultListT);
			logger.info("分页查找商品成功！");
		}catch(Exception e){
			logger.error("分页查找商品失败！"+e);
			throw new ScBizException("分页查找商品错误！", e);
		}
		return mav;
	}
	/***
	 * 查看更多热销产品( 根据分类ID查询)
	 * @param request
	 * @return
	 */
	/*@RequestMapping(value="/findMoreHotSale")
	@ResponseBody
	public Object findMoreHotSale(HttpServletRequest request){
		
		
		
		return null;
	}*/
	
	
	/**
	 * 新品推荐
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="newProducts", method=RequestMethod.GET)
	public Object newProducts(HttpServletRequest request,Integer currPage, Integer pageSize){
		ModelAndView mav = new ModelAndView("/goods/new_products");
		List<Map<String, Object>> resultList = null;
		int totalRecords = 0;
		int totalPage = 0;
		//参数
		Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
		String search = request.getParameter("search");
		
		if(StringUtils.isNotBlank(search)){
			paramMap.put("search", search);
		}
		//01：特别推荐、02：热销、03:特价、09：包邮
		paramMap.put("type", "01");
		try{
			//搜索商品
			PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count", "selectList", GoodsMapper.class);
			
			resultList = paginationBean.getPageList();
			totalRecords = paginationBean.getTotalRecords();
			totalPage = paginationBean.getTotalPage();
			
			request.setAttribute("resultList", resultList);
			request.setAttribute("totalRecords", totalRecords);
			request.setAttribute("totalPage", totalPage);
			
			String weekTime = DateUtil.getWeekTime();
			paramMap.put("createTime", weekTime);
			//获取当前一周的数据
			List<Goods> GoodsWeekList = goodsService.queryGoodsByClassIdList(paramMap);
			if(GoodsWeekList.size()>0){
				mav.addObject("GoodsWeekList", GoodsWeekList);
			}
			  for (int i = 0; i < resultList.size(); i++) {
					Goods goods = (Goods) resultList.get(i);
					Integer id = goods.getId();
					String goodsType = goods.getType();
					//***获取该商品的月销量****************//
					int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(id);	
					goods.setMonthSaleMount(String.valueOf(monthSaleMount));
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("goodsId", id);
					String proTitle="";
					if(goodsType!=null){
						String goodstypeTemp[] = goodsType.split("-");
						for(int j =0;j<goodstypeTemp.length;j++ ){
							if("09".equals(goodstypeTemp[j])){
								proTitle="包邮、";
							}
				         }
					}
					proTitle += promotionService.getGoodsByPromtion(map);
					/**  截取字段*/
					if(proTitle.endsWith("、")){
						proTitle = proTitle.substring(0, proTitle.length()-1);
					}
					goods.setProTitle(proTitle);
					
				}
			logger.info("分页查找商品成功！");
		
		}catch(Exception e){
			logger.error("分页查找商品失败！"+e);
			throw new ScBizException("分页查找商品错误！", e);
		}
		
		return mav;
		
	}
	
	/**
	 * 特价产品
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="specialPro", method=RequestMethod.GET)
	public Object specialPro(HttpServletRequest request,Integer currPage, Integer pageSize){
		ModelAndView mav = new ModelAndView("/goods/special_pro");
		List<Map<String, Object>> resultList = null;
		int totalRecords = 0;
		int totalPage = 0;
		pageSize = 50;
		//参数
		Map<String,Object> paramMap = new LinkedHashMap<String,Object>();
		String search = request.getParameter("search");
		
		if(StringUtils.isNotBlank(search)){
			paramMap.put("search", search);
		}
		//01：特别推荐、02：热销、03:特价、09：包邮
			paramMap.put("type", "03");
		try{
			//搜索商品
			PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "count", "selectList", GoodsMapper.class);
			
			resultList = paginationBean.getPageList();
			totalRecords = paginationBean.getTotalRecords();
			totalPage = paginationBean.getTotalPage();
			
			request.setAttribute("resultList", resultList);
			request.setAttribute("totalRecords", totalRecords);
			request.setAttribute("totalPage", totalPage);
			
			logger.info("分页查找商品成功！");
		}catch(Exception e){
			logger.error("分页查找商品失败！"+e);
			throw new ScBizException("分页查找商品错误！", e);
		}
		
		return mav;
		
	}
	
	
	
	
	
	/***
	 * 根据商品分类ID 查询商品列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryGoodsByClassIdList")
	@ResponseBody
	public Object queryGoodsByClassIdList(HttpServletRequest request,Integer currPage, Integer pageSize){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/*String classId = request.getParameter("classId");
		if(StringUtils.isNotBlank(classId)){
			map.put("classId", classId);
		}
		List<Goods> GoodsList = goodsService.queryGoodsByClassIdList(map);
		return GoodsList;*/
		
		String classId = request.getParameter("classId");
		String className = request.getParameter("className");
		List<Map<String, Object>> resultList = null;
		int totalRecords = 0;
		int totalPage = 0;
		pageSize = 50;
		Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
		if(StringUtils.isNotBlank(classId)){
			paramMap.put("classId", classId);
		}
		try{
			//根据分类ID搜索商品
			PaginationBean<Map<String,Object>> paginationBean = this.goodsService.getPagingDatas(paramMap, currPage, pageSize, "queryGoodsByClassIdCount", "queryGoodsByClassIdList", GoodsMapper.class);
			resultList = paginationBean.getPageList();
			totalRecords = paginationBean.getTotalRecords();
			totalPage = paginationBean.getTotalPage();
			int currentPage = paginationBean.getCurrentPage();
			resultMap.put("resultList", resultList);
			resultMap.put("totalRecords", totalRecords);
			resultMap.put("totalPage", totalPage);
			resultMap.put("currentPage", currentPage);

			for (int i = 0; i < resultList.size(); i++) {
				Goods goods = (Goods) resultList.get(i);
				Integer id = goods.getId();
				String goodsType = goods.getType();
				//***获取该商品的月销量****************//
				int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(id);	
				goods.setMonthSaleMount(String.valueOf(monthSaleMount));
				Map<String, Object> map = new LinkedHashMap<String, Object>();
				map.put("goodsId", id);
				String proTitle="";
				if(goodsType!=null){
					String goodstypeTemp[] = goodsType.split("-");
					for(int j =0;j<goodstypeTemp.length;j++ ){
						if("09".equals(goodstypeTemp[j])){
							proTitle="包邮、";
						}
			         }
				}
				proTitle += promotionService.getGoodsByPromtion(map);
				/**  截取字段*/
				if(proTitle.endsWith("、")){
					proTitle = proTitle.substring(0, proTitle.length()-1);
				}
				goods.setProTitle(proTitle);
			}
			logger.info("分页查找商品成功！");
		}catch(Exception e){
			logger.error("分页查找商品失败！"+e);
			throw new ScBizException("分页查找商品错误！", e);
		}
		return resultMap;
	}
	
	/**
	 * pc端首页： 人气推荐的商品
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/selectListRecommend")
	@ResponseBody
	public Object selectListRecommend(HttpServletRequest request){
		List<Goods> GoodsList = goodsService.selectListRecommend();
		return GoodsList;
	}
	/***
	 * 根据id查看商品详细信息
	 * @param id 2
	 * mId 111111
	 * @return  mId
	 */
	@RequestMapping(value="queryGoodsDetail")
	@ResponseBody
	public ModelAndView queryGoodsDetail(HttpServletRequest request,Integer id,String mId){
		
		DecimalFormat df = new DecimalFormat("######0.00");   
		ModelAndView mav = new ModelAndView("goods/store");
//		UserFormMap user = (UserFormMap) request.getSession().getAttribute("userSession");
		Member member = SessionContainer.getSessionMember(request);// 根据sessionId获取登录用户
		if(id==null){
			logger.warn("查询参数为null！");
		}else {
			try{
				String meberId ="";
				if(member!=null){
					meberId = member.getmId(); ////记录会员ID
				}
				Goods goods = this.goodsService.selectByPrimaryKey(id,meberId);
				Map<String, Object> agentInfoMap = null;
				//判断会员是否登录，如果登录则是会员价格。
				if(StringUtils.isNotBlank(meberId)){
					agentInfoMap = memberService.selectAgentInfoByMemberId(meberId);
					if(agentInfoMap != null && agentInfoMap.size() >0){
						if( agentInfoMap.get("discount") != null){
							String count = agentInfoMap.get("discount").toString();
							BigDecimal marketPrice = goods.getMarketPrice();
							if(marketPrice!=null){
								double price = marketPrice.multiply(new BigDecimal(count)).doubleValue();
//								goods.setMarketPrice(new BigDecimal(df.format(price)).setScale(2, BigDecimal.ROUND_HALF_UP));
								goods.setMemberMarketPrice(new BigDecimal(df.format(price)));
							}
						}
					}else{
						goods.setMemberMarketPrice(goods.getMarketPrice());
					}
				}
				if(goods!=null){
					//根据该商品的分类ID获取相关的商品信息，前台展现于看了又看的商品
					/**展现于看了又看的商品***/
					String classId = goods.getClassId();
					if(classId!=null && !"".equals(classId)){
						Map<String, Object> classMap = new HashMap<String, Object>();
						classMap.put("classId", classId);
						classMap.put("creater", meberId);
//						List<Goods> goodsList = goodsService.queryGoodsByClassIdList(classMap);
						List<ConsultComment> commentList = consultCommentService.queryLatelyTracks(classMap);
						mav.addObject("seeGoodsListA", commentList);
					}
					List<GoodsClass> GoodsClassList = goodsClassService.selectByGoodsClass();
					mav.addObject("GoodsClassList", GoodsClassList);
					
					/**统计商品评价、交易成功数****/
					List<Integer> totalCount = goodsService.statisticsGoodsDetails(id);
					mav.addObject("totalCount", totalCount);
					mav.addObject("member", member);
					/**看了该商品的还看了哪些商品信息***/
					Map<String, Object> idMap = findGoodsByList(id);
					List<Goods> seeGoodsList = goodsService.queryGoodsListById(idMap);
					mav.addObject("seeGoodsListB", seeGoodsList);
					mav.addObject("goodsDetail", goods);
					logger.warn("查询商品详情成功！");
				}else{
					logger.warn("查询商品详情失败！");
				}
			}catch(Exception e){
				logger.error("查询商品数据异常"+e);
				throw new ScBizException("查询商品数据异常！", e);
			}
		}
		return mav;
	}

	
	/****
	 * 根据商品id
	 * 查询看了该商品的人还看了哪些商品
	 * 1、在足迹表根据商品ID获取人员
	 * 2、根据人员获取商品ID
	 * @param id
	 * @return
	 */
	public Map<String, Object> findGoodsByList(Integer id){
		Map<String, Object> idMap = new HashMap<String, Object>();
		/**根据商品ID获取相关的人员信息【取5条数据】***/
		Map<String, Object> manMap = new HashMap<String, Object>();
		String tempMan = "";
		List<String> stringList = consultCommentService.findConsultByGoodsId(id);
		if(stringList!=null && stringList.size()>0){
			for (String string : stringList) {
				tempMan+="'"+string+"',";
			}
			tempMan=tempMan.substring(0, tempMan.length()-1);
			manMap.put("creater", tempMan);
		}
		/**在根据人员信息获取相关的商品信息【取8条数据】***/
		String goodsId = "";
		List<String> idList = consultCommentService.findConsultByCreater(manMap);
		if(idList!=null && idList.size()>0){
			for (String string : idList) {
				goodsId+="'"+string+"',";
			}
			goodsId=goodsId.substring(0, goodsId.length()-1);
			idMap.put("goodsId", goodsId);
		}
		return idMap;
	}
	
	/**
	 * @Title: goodsCollectionsentiment
	 * @Description 查询商品收藏人气数量
	 * @param goodsId
	 * @date 2017年5月9日下午14:53:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="goodsCollectionSentiment",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> goodsCollectionSentiment(Integer goodsId){
		Map<String,Object> paramMap = new LinkedHashMap<String, Object>();
		List<Favorites> list =null;
		try{
			if(goodsId == null){			
				DataUtil.handleResultMap(paramMap, ExceptionEnum.DATA_PARAM);
				return paramMap;
			}
			paramMap.put("goodsId", goodsId);
			list =  goodsService.goodsCollectionSentiment(paramMap);	
			if(list != null ){
				paramMap.put("count", list.size());
			}else{
				paramMap.put("count", 0);
			}
			DataUtil.handleResultMap(paramMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(paramMap, ExceptionEnum.DATA_SELECT);
		}
		
		return paramMap;
	}
	/**
	 * @Title: goodsProList
	 * @Description 查询商品参与的促销活动
	 * @param goodsId
	 * @date 2017年5月10日上午09:34:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="goodsProList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> goodsProList(Integer goodsId,HttpServletRequest request){
		Map<String,Object> resultMap = new LinkedHashMap<String, Object>();
		try{
			if(goodsId == null){			
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}

			//List<Map<String,Object>> goodsProMapList = new ArrayList<Map<String, Object>>();
			//查询商品参与的促销活动
			List<PromotionGoodsSkuDto>  goodsProList = promotionService.getGoodsProInfo(goodsId);
			if(goodsProList != null && goodsProList.size() > 0){
				for(PromotionGoodsSkuDto goodsSkuDto : goodsProList){	
					List<Map<String, Object>> proDetailMapList = goodsSkuDto.getProDetailMapList();
					List<PromotionDetailDto> goodsProDetailList = promotionService.selectProDetailByProId(goodsSkuDto.getPro_id());
					for(PromotionDetailDto proDetailDto :goodsProDetailList){
                        Date now_time = new Date(); //现在时间
					    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
					    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
					    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
							Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
							//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
							proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
							proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
							proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
							String pro_type = proDetailDto.getPro_type();
							String pro_money = proDetailDto.getPro_money();
							String pro_count = proDetailDto.getPro_count();
							String pro_rate = proDetailDto.getPro_rate();								

							String pro_gooods = proDetailDto.getPro_goods();
							proDetailMap.put("productId",goodsId);
							proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
							proDetailMap.put("proType", pro_type);//促销类型
							proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
							proDetailMapList.add(proDetailMap);
						
					    }
					}
				}
			}
			resultMap.put("data", goodsProList);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultMap;
		
	}
	
	
	/**
	 * @Title: goodsProList
	 * @Description 查询商品参与的促销活动
	 * @param goodsId
	 * @date 2017年5月10日上午09:34:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	public List<PromotionGoodsSkuDto> goodsProListAll(Integer goodsId){
		Map<String,Object> resultMap = new LinkedHashMap<String, Object>();
		try{
			if(goodsId == null){			
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
//				return resultMap;
			}
			//查询商品参与的促销活动
			List<PromotionGoodsSkuDto>  goodsProList = promotionService.getGoodsProInfo(goodsId);
			if(goodsProList != null && goodsProList.size() > 0){
				for(PromotionGoodsSkuDto goodsSkuDto : goodsProList){	
					List<Map<String, Object>> proDetailMapList = goodsSkuDto.getProDetailMapList();
					List<PromotionDetailDto> goodsProDetailList = promotionService.selectProDetailByProId(goodsSkuDto.getPro_id());
					for(PromotionDetailDto proDetailDto :goodsProDetailList){
                        Date now_time = new Date(); //现在时间
					    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
					    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
					    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
							Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
							//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
							proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
							proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
							proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
							String pro_type = proDetailDto.getPro_type();
							String pro_money = proDetailDto.getPro_money();
							String pro_count = proDetailDto.getPro_count();
							String pro_rate = proDetailDto.getPro_rate();								

							String pro_gooods = proDetailDto.getPro_goods();
							proDetailMap.put("productId",goodsId);
							proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
							proDetailMap.put("proType", pro_type);//促销类型
							proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
							proDetailMapList.add(proDetailMap);
						
					    }
					}
				}
			}
//			resultMap.put("data", goodsProList);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			return goodsProList;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
		
	}
	/**
	 * 封装促销活动返回集合
	 * @param proDetailMap
	 * @param pro_type
	 * @param pro_money
	 * @param pro_count
	 * @param pro_rate
	 * @param pro_gooods
	 * @return
	 */
	public Map<String ,Object> proDetailMap(Map<String ,Object> proDetailMap,String pro_type,String pro_money,String pro_count,String pro_rate,String pro_gooods){
		 List<Goods> goodsList =new ArrayList<Goods>();//满赠商品列表  
			String[] goods_ids =null;
			if(Common.isNotEmpty(pro_gooods)){
				goods_ids =pro_gooods.split(",");
				for(String goods_id : goods_ids){
					Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(goods_id));
					goodsList.add(goods);
				}
			}
		switch(pro_type){
			case "0": //订单满减
				if(Common.isNotEmpty(pro_money)){
					proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
					proDetailMap.put("discountAmount", pro_money.split(":")[1]);
				}
				break;
			case "1": //商品满减
				if(Common.isNotEmpty(pro_count)){
					proDetailMap.put("mustQuantity ", pro_count.split(":")[0]);
					proDetailMap.put("discountAmount", pro_count.split(":")[1]);
				}
				break;
			case "2": //商品满赠
				if(Common.isNotEmpty(pro_count)){
					proDetailMap.put("mustQuantity", pro_count.split(":")[0]);
					proDetailMap.put("giveNumber", pro_count.split(":")[1]);
					proDetailMap.put("giveList", goodsList);
				}
				break;
			case "3":  //商品打折
				if(Common.isNotEmpty(pro_count)){
					proDetailMap.put("mustQuantity", pro_count);//商品满足数量
					BigDecimal rate = new BigDecimal(new Double(pro_rate)/100).setScale(2, BigDecimal.ROUND_HALF_UP);
					proDetailMap.put("discountRate",rate.toString());//商品打折率
				}
				break;
		}
		return proDetailMap;
	}
	
	/*********
	 * 组装商品月销量、商品优惠信息
	 * @param resultListExt
	 * @return
	 */
	public List<Map<String, Object>> getGoodsByFavourable(List<Map<String, Object>> resultListExt){
		List<Map<String, Object>> resultList = resultListExt;
		for (int i = 0; i < resultList.size(); i++) {
			Goods goods = (Goods) resultList.get(i);
			Integer id = goods.getId();
			String goodsType = goods.getType();
			//***获取该商品的月销量****************//
			int monthSaleMount =  goodsService.selectGoodsMonthSaleMount(id);	
			goods.setMonthSaleMount(String.valueOf(monthSaleMount));
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("goodsId", id);
			String proTitle="";
			if(goodsType!=null){
				String goodstypeTemp[] = goodsType.split("-");
				for(int j =0;j<goodstypeTemp.length;j++ ){
					if("09".equals(goodstypeTemp[j])){
						proTitle="包邮、";
					}
		         }
			}
			proTitle += promotionService.getGoodsByPromtion(map);
			/**  截取字段*/
			if(proTitle.endsWith("、")){
				proTitle = proTitle.substring(0, proTitle.length()-1);
			}
			goods.setProTitle(proTitle);
		}
		return resultList;
	}
}
